package com.firewolf.fr.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.firewolf.fr.pojo.Mobile;
import com.firewolf.fr.utils.SolrUtil;

@Service
public class TestServiceImpl {

	@Value("${solrurl.mobile}")
	private String solrurl;

	public List<Mobile> searchMobile(String keyWords) {
		if (keyWords != null)
			try {
				keyWords = new String(keyWords.getBytes("ISO-8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		HttpSolrClient server = SolrUtil.getServer(solrurl);
		SolrQuery q = new SolrQuery();
		String sql = "*:*";
		if(keyWords != null){
			sql = "search:" + keyWords;
		}
		q.set("q", sql);
		q.setHighlight(true);
		q.addHighlightField("pname");
		q.addHighlightField("brand");
		q.addHighlightField("wlan");
		q.addHighlightField("color");
	    q.setHighlightSnippets(1);
	    q.setHighlightFragsize(100);
		q.setHighlightSimplePre("<font color='red'>");
		q.setHighlightSimplePost("</font>");
		try {
			QueryResponse query = server.query(q);
			List<Mobile> beans = query.getBeans(Mobile.class);
			Map<String, Map<String, List<String>>> highlightresult = query.getHighlighting();
			if (beans.size() > 0 && highlightresult.size() > 0) {
				for(Mobile m : beans){
					Map<String, List<String>> map = highlightresult.get(m.getId());
					if(map.get("pname") != null)
						m.setPname(map.get("pname").get(0));
					if(map.get("brand") != null)
						m.setBrand(map.get("brand").get(0));
					if(map.get("color") != null)
						m.setColor(map.get("color").get(0));
					if(map.get("wlan") != null)
						m.setWlan(map.get("wlan").get(0));
					
				}
			}

			return beans;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
